package com.yunc.modules.shop.handler;

import com.alibaba.fastjson.JSON;
import com.yunc.common.exception.UCException;
import com.yunc.common.message.AbstractMessageHandler;
import com.yunc.common.utils.BaseConstant;
import com.yunc.modules.shop.entity.*;
import com.yunc.modules.shop.entity.vo.OrderItemVO;
import com.yunc.modules.shop.entity.vo.OrderVO;
import com.yunc.modules.shop.service.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 处理订单
 *
 * @author taocongcong
 * @create 2018-11-21 14:26
 */
@Service
public class OrderHandler extends AbstractMessageHandler<OrderVO> {

    private static final Logger logger = LogManager.getLogger(AbstractMessageHandler.class);

    @Autowired
    private IItemService itemService;
    @Autowired
    private IItemSpecsService itemSpecsService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private IOrderItemService orderItemService;

    public OrderHandler() {
        super("CREATE_ORDER_SHOP", OrderVO.class);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class, UCException.class})
    public synchronized void handle(OrderVO orderInfo) {
        // 生成订单
        Order order = new Order();
        order.setMemberId(orderInfo.getMemberId());
        order.setOrderNumber(orderInfo.getOrderNumber());
        order.setStatus(BaseConstant.OrderStatus.PAY.getValue());
        order.setPaymentTime(new Date());
        order.setPayment(orderInfo.getPayment());
        order.setAddressId(orderInfo.getAddressId());
        // 地址
        Address address = addressService.getById(orderInfo.getAddressId());
        if (address != null) {
            order.setAddressName(address.getName());
            order.setAddressPhone(address.getPhone());
            order.setAddressDescripts(address.getDescripts());
        }
        order.setRemoveTag(BaseConstant.REMOVE_Y);
        order.setCreateTime(new Date());
        boolean flag = orderService.save(order);
        // order表的主键
        if (flag) {
            List<OrderItemVO> orderItemList = JSON.parseArray(orderInfo.getOrderItemJson(), OrderItemVO.class);
            if (orderItemList != null && orderItemList.size() > 0) {
                for (OrderItemVO orderItemD : orderItemList) {
                    Item item = itemService.getById(orderItemD.getItemId());
                    if (item == null) {
                        continue;
                    }
                    // 减库存操作
                    if (orderItemD.getSpecsSeq() == null) {
                        // 判断库存数
                        if (item.getNum() >= orderItemD.getNum()) {
                            // 减去库存
                            item.setNum(item.getNum() - orderItemD.getNum());
                            itemService.saveOrUpdate(item);
                        } else {
                            throw new UCException("您选择的商品库存不足!");
                        }
                    } else {
                        // 改变库存值
                        ItemSpecs itemSpecs = itemSpecsService.getById(orderItemD.getSpecsSeq());
                        // 判断库存数
                        if (itemSpecs.getStock() >= orderItemD.getNum()) {
                            // 减去库存
                            itemSpecs.setStock(itemSpecs.getStock() - orderItemD.getNum());
                            itemSpecsService.saveOrUpdate(itemSpecs);
                        } else {
                            throw new UCException("您选择的商品库存不足!");
                        }
                    }
                    OrderItem orderItem = new OrderItem();
                    orderItem.setOrderId(order.getId());
                    orderItem.setItemId(orderItemD.getItemId());
                    orderItem.setSpecsId(orderItemD.getSpecsSeq());
                    orderItem.setNum(orderItemD.getNum());
                    orderItem.setParamData(orderItemD.getParamData());
                    orderItem.setTitle(item.getTitle());
                    orderItem.setPrePrice(item.getPrePrice());
                    orderItem.setOrigPrice(item.getOrigPrice());
                    orderItem.setImage(item.getImage());
                    orderItem.setTotalPrice(item.getPrePrice() * orderItemD.getNum());
                    orderItem.setCreateTime(new Date());
                    orderItemService.save(orderItem);
                }
            }
        }
    }

    @Override
    public void handleFailed(OrderVO obj) {
        StringBuilder sb = new StringBuilder();
        sb.append("msg:[").append(obj).append("], 超过失败次数，停止重试。");
        logger.warn(sb.toString());
    }
}
